<?php

/*
 * This file is part of ibrand/EC-Open-Server.
 *
 * (c) iBrand <https://www.ibrand.cc>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace iBrand\EC\Open\Server\Http\Controllers;

use Cart;
use iBrand\Component\Product\Models\Goods;
use iBrand\Component\Product\Models\Product;
use iBrand\EC\Open\Backend\Store\Repositories\GoodsRepository;
use iBrand\EC\Open\Server\Transformers\GoodsTransformer;
use Illuminate\Support\Facades\Redis;
use DB;

class ShoppingCartController extends Controller
{
    protected $discountService;
    protected $goodsUserLimit;
    protected $goodsLimit;
    protected $goodsRepository;

    public function __construct(GoodsRepository $goodsRepository)
    {
        $this->goodsRepository = $goodsRepository;
    }

    public function index()
    {
        if (empty(request()->all())) {
            $carts = Cart::search(['channel' => 'normal']);
        } else {
            $carts = Cart::search(request()->all());
        }

        //返回购物车中目前所有商品的库存
        foreach ($carts as $item) {
            if ($item and $item->model) {
                $item['stock_qty'] = $item->model->stock_qty;
            } else {
                $item['stock_qty'] = 0;
            }
        }

        return $this->success($carts);
    }


    public function addCart(){
        $carts = request()->all();
        $user_id = request()->user()->id;
        $key = 'cart_'.$user_id;
        //判断购物车是否有商品 如果有 拿出来添加 然后更新 如果没有直接新建然后添加
        $goods_info = Redis::get($key);
        if(!$goods_info){
            $goods_infos [] = $carts;
        }else{
            $goods_infos = json_decode($goods_info,true);
            $isHave = false;
            foreach ($goods_infos as &$v){
               if(($v['id'] == $carts['id']) && ($v['sku'] == $carts['sku'])){
                    $isHave = true;
                    $v['goods_num'] += $carts['goods_num'];
               }
            }
            if(!$isHave){
                $goods_infos[] = $carts;
            }
        }
        foreach ($goods_infos as &$itme){
            $goods = DB::table('ibrand_goods')->where(['id'=>$itme['id']])->first(['name','img']);
            if($goods){
                $goods_product = DB::table('ibrand_goods_product')->where(['goods_id'=>$itme['id'],'sku'=>$itme['sku']])->first(['spec_ids','sell_price']);
                $itme['goods_name'] = $goods->name;
                $itme['img'] = $goods->img;
                $itme['sell_price'] = $goods_product->sell_price;
            }else{
                unset($itme);
                continue;
            }
        }
        $cart_list = json_encode($goods_infos);
        Redis::set($key,$cart_list);
        return $this->success('添加成功！');

    }
    //获取购物车信息
    public function getCart(){
        $user_id = request()->user()->id;
        $key = 'cart_'.$user_id;
        $goods_info = Redis::get($key);
        $goods_infos = json_decode($goods_info);
        return $this->success($goods_infos);
    }

    /**
     * @return \Dingo\Api\Http\Response|mixed
     * 编辑购物车
     */
    public function editCart(){
        $user_id = request()->user()->id;
        $id = request('sku');
        $goods_num = request('goods_num');
        $key = 'cart_'.$user_id;
        $goods_info = Redis::get($key);
        if(!$goods_info){
            return $this->failed('暂无商品！');
        }
        $goods_infos = json_decode($goods_info,true);
        $found_key = array_search($id, array_column($goods_infos, 'sku'));
        if($found_key===false){
            return $this->failed('暂无商品！');
        }
        $goods_infos[$found_key]['goods_num'] = $goods_num;
        $cart_list = json_encode($goods_infos);
        Redis::set($key,$cart_list);
        return $this->success('修改成功！');
    }

    /**
     * @return \Dingo\Api\Http\Response|mixed
     * 删除购物车
     */
    public function delCart(){
        $user_id = request()->user()->id;
        $id = request('sku');
        $key = 'cart_'.$user_id;
        $goods_info = Redis::get($key);
        if(!$goods_info){
            return $this->failed('暂无商品！');
        }
        $goods_infos = json_decode($goods_info,true);
        $found_key = array_search($id, array_column($goods_infos, 'sku'));
        if($found_key===false){
            return $this->failed('暂无商品！');
        }
        unset($goods_infos[$found_key]);
        $goods_infoss =  array_values($goods_infos);
        $cart_list = json_encode($goods_infoss);
        Redis::set($key,$cart_list);
        return $this->success('删除成功');
    }







    public function store()
    {
        $carts = request()->all();

        if (0 == count($carts)) {
            return $this->success();
        }

        foreach ($carts as $cart) {
            //设置属性值
            $attributes = isset($cart['attributes']) ? $cart['attributes'] : [];

            if (isset($cart['attributes']) and !isset($cart['attributes']['sku'])) {
                Cart::associate(Goods::class);
                $attributes['type'] = 'spu';
            } else {
                Cart::associate(Product::class);
                $attributes['type'] = 'sku';
            }

            if (!isset($cart['id'])) {
                continue;
            }

            //var_dump($cart);
            $item = Cart::add($cart['id'], $cart['name'], $cart['qty'], $cart['price'], $attributes);
            if (!$item || !$item->model) {

                //var_dump($item->model);
                return $this->failed('商品数据错误');
            }

            if (2 == $item->model->is_del) {
                //已下架，需要删除购物车数据
                Cart::remove($item->rawId());

                return $this->failed('商品已下架');
            }

            if (($qty = $this->getIsInSaleQty($item, $item->qty)) > 0) {
                Cart::update($item->rawId(), ['qty' => $qty]);
            } else {
                Cart::remove($item->rawId());

                return $this->failed( '商品库存不足,请重新选择');
            }

            Cart::update($item->rawId(), ['status' => 'online', 'market_price' => $item->model->market_price, 'channel' => 'normal']);
        }

        return $this->success(Cart::all());
    }

    public function update($id)
    {
        $item = Cart::get($id);

        if (!$item) {
            return $this->failed('购物车数据不存在');
        }

        $attributes = request('attributes');

        if ($attributes['qty'] <= $item->model->stock_qty) {
            $item = Cart::update($id, $attributes);

            return $this->success($item);
        }

        return $this->failed('库存不够');
    }

    public function delete($id)
    {
        return $this->success(Cart::remove($id));
    }

    public function clear()
    {
        Cart::destroy();

        return $this->success(Cart::all());
    }

    public function count()
    {
        return $this->success(Cart::count());
    }

    public function getIsInSaleQty($item, $qty)
    {
        if ($qty <= 0) {
            return 0;
        }
        if ($item->model->getIsInSale($qty)) {
            return $qty;
        }

        return $this->getIsInSaleQty($item, $qty - 1);
    }
}
